package com.study.zzedu.fragment.notice;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.study.zzedu.R;
import com.study.zzedu.adapter.NoticeAdapter;
import com.study.zzedu.adapter.YiDongAdapter;
import com.study.zzedu.base.BaseFragment;
import com.study.zzedu.entity.NoticeItem;
import com.study.zzedu.entity.YiDongModel;
import com.study.zzedu.ui.noticeinfodetail.NoticeInfoDetailActivity;
import com.study.zzedu.ui.yidonginfo.YiDongInfoActivity;
import com.study.zzedu.utils.AppConstant;
import com.study.zzedu.utils.LogUtil;
import com.study.zzedu.utils.ToastUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kiros on 2020/9/3.
 */

public class NoticeFragment extends BaseFragment<NoticeContract.IView,NoticePresenter> implements NoticeContract.IView, View.OnClickListener, OnBannerListener {

    public Banner banner;
    public RecyclerView rl_notice;
    private RecyclerView.LayoutManager layoutManager;
    private NoticeAdapter noticeAdapter;
    private List<NoticeItem> noticeItems = new ArrayList<NoticeItem>();
    private List imgs = new ArrayList<>();
    private List titles = new ArrayList<>();
    private List img_tolink = new ArrayList<>();
    @Override
    protected NoticePresenter createPresenter() {
        return new NoticePresenter();
    }

    @Override
    protected NoticeContract.IView createView() {
        return this;
    }


    @Override
    protected int getLayoutID() {
        return R.layout.fragment_notice_all;
    }

    @Override
    protected void initView(View view) {
        banner = view.findViewById(R.id.banner1);
        banner.setVisibility(View.GONE);
        rl_notice = view.findViewById(R.id.rl_notice);
    }

    @Override
    protected void initData() {
        layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        //getPresenter().getInfoList(getContext());
        //getPresenter().getImgList(getContext());
        getPresenter().getInfoList(getContext());
    }

    @Override
    protected void initListener() {}

    private void setBanner() {
        //imgs.add(getStringFromDrawableRes(getContext(), R.drawable.zu1));
        //imgs.add("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1346142700,2282998096&fm=26&gp=0.jpg");
        //titles.add("教育图片1");
        //设置内置样式，共有六种可以点入方法内逐一体验使用。
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
        //设置图片加载器，图片加载器在下方
        banner.setImageLoader(new MyLoader());
        //设置图片网址或地址的集合
        banner.setImages(imgs);
        //设置轮播的动画效果，内含多种特效，可点入方法内查找后内逐一体验
        banner.setBannerAnimation(Transformer.Default);
        //设置轮播图的标题集合
        banner.setBannerTitles(titles);
        //设置轮播间隔时间
        banner.setDelayTime(3000);
        //设置是否为自动轮播，默认是“是”。
        banner.isAutoPlay(true);
        //设置指示器的位置，小点点，左中右。
        banner.setIndicatorGravity(BannerConfig.CENTER)
        //以上内容都可写成链式布局，这是轮播图的监听。比较重要。方法在下面。
                .setOnBannerListener(this)
        //必须最后调用的方法，启动轮播图。
                .start();
    }

    @Override
    public void OnBannerClick(int position) {
        LogUtil.e("notice","你点了第"+position+"张轮播图");
    }

    @Override
    public void getInfoListCallBack(String data) {
        noticeItems.clear();
        try {
            JSONObject jObject = new JSONObject(data);
            JSONArray jArray = jObject.getJSONArray("data");
            for (int i = 0;i<jArray.length();i++){
                try {
                    noticeItems.add(new NoticeItem
                            (jArray.getJSONObject(i).getString("id"),jArray.getJSONObject(i).getInt("hasRead"),
                                    jArray.getJSONObject(i).getString("title"),
                                    jArray.getJSONObject(i).getString("createDate")
                            ));
                }catch (Exception e){
                    e.toString();
                }
            }
            if(jArray.length()<1){
                ToastUtil.showShortToast("无通知消息");
                return;
            }
            getActivity().findViewById(R.id.rl_default_notice_all).setVisibility(View.GONE);
        } catch (Exception e) {
            e.toString();
        }
        noticeAdapter = new NoticeAdapter(getContext(), noticeItems);
        onChange.onChange(isHasUnRead(noticeItems));
        noticeAdapter.setOnItemClickListener(new NoticeAdapter.OnItemClickListner() {
            @Override
            public void onClick(int position) {
                //ToastUtil.showShortToast("posi:"+position);
                NoticeItem nItem = noticeItems.get(position);
                Intent intent = new Intent(getContext(), NoticeInfoDetailActivity.class);
                intent.putExtra("infoID",nItem.getId());
                intent.putExtra("from", AppConstant.NOTICE);
                startActivityForResult(intent,position);
            }
        });
        rl_notice.setLayoutManager(layoutManager);
        rl_notice.setAdapter(noticeAdapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(noticeItems != null){
            //设置对应item为已读
            noticeItems.get(requestCode).setStatus(1);
            onChange.onChange(isHasUnRead(noticeItems));
            noticeAdapter.notifyItemChanged(requestCode);
        }
    }

    //true : 无未读  false：有未读
    public boolean isHasUnRead(List<NoticeItem> noticeItems){
        for (NoticeItem item : noticeItems){
            if(0 == item.getStatus())
                return false;
        }
        return true;
    }
    @Override
    public void getImgList(String data) {
        //ToastUtil.showShortToast("获得img-list");
        try {
            JSONObject jObject = new JSONObject(data);
            JSONArray jArray = jObject.getJSONArray("data");
            for (int i = 0;i<jArray.length();i++){
                imgs.add(jArray.getJSONObject(i).getString("uri"));
                titles.add(jArray.getJSONObject(i).getString("title"));
                img_tolink.add(jArray.getJSONObject(i).getString("linkUrl"));
            }
            if(jArray.length()>0)
            setBanner();
        } catch (Exception e) {
            e.toString();
        }
        getPresenter().getInfoList(getContext());
    }

    @Override
    public void getData(String data) {
    }

    @Override
    public void showError(String error) {
        if (null != error && ! TextUtils.isEmpty(error)) {
            ToastUtil.showShortToast(error);
        }
    }

    //自定义的图片加载器
    private class MyLoader extends ImageLoader {

        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Glide.with(context).load((String) path).into(imageView);
        }
    }

    public static String getStringFromDrawableRes(Context context, int id) {
        Resources resources = context.getResources();
        String path = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + resources.getResourcePackageName(id) + "/"
                + resources.getResourceTypeName(id) + "/"
                + resources.getResourceEntryName(id);
        return path;

    }

    @Override
    public void onClick(View v) {

    }

    public static OnCountChange onChange;

    public interface OnCountChange{
        void onChange(boolean unRead);
    }
    public static void  setOnNoticeCountChange(OnCountChange change){
        onChange = change;
    }
}
